<?php

namespace App\Models;


use App\Models\User;
use Illuminate\Database\Eloquent\Builder;

class Order extends Model
{
    const STATUS_INIT = 0;
    const STATUS_PAYING = 1;
    const STATUS_PAY_SUCCESS = 2;
    const STATUS_PAY_FAIL = 3;
    const STATUS_TIMEOUT = 4;
    const STATUS_CANCEL = 5;

    public static $statusText = [
        self::STATUS_INIT => '未支付',
        self::STATUS_PAYING => '未支中',
        self::STATUS_PAY_SUCCESS => '支付成功',
        self::STATUS_PAY_FAIL => '支付失败',
        self::STATUS_TIMEOUT => '超时未支持',
        self::STATUS_CANCEL => '已取消',
    ];

    const GOODS_TYPE_TOPIC = 1;

    public static $goodsTypeText = [
        self::GOODS_TYPE_TOPIC => '帖子',
    ];

    const PAY_TYPE_SCORE = 1;

    public static $payTypeText = [
        self::PAY_TYPE_SCORE => '积分',
    ];


    protected $fillable = [
        'uid', 'goods_type', 'goods_id', 'pay_type', 'trade_no', 'out_trade_no',
        'price', 'status', 'remark', 'snapshot', 'request_id', 'paid_at', 'canceled_at'
    ];

    public static function booted()
    {
        static::creating(function ($model) {
            $model->request_id = REQUEST_ID;
            $model->trade_no = sprintf(
                '%s%s',
                date('YmdHis'),
                substr(str_replace('.', '', microtime(true)), -4)
            );
        });
    }

    public function getStatusTextAttribute()
    {
        return self::$statusText[$this->status] ?? '';
    }

    public function getGoodsTypeTextAttribute()
    {
        return self::$goodsTypeText[$this->goods_type] ?? '';
    }

    public function getPayTypeTextAttribute()
    {
        return self::$payTypeText[$this->pay_type] ?? '';
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'uid');
    }

    public function scopeGoodsTypeIsTopic(Builder $query, $tid)
    {
        return $query->where('goods_type', self::GOODS_TYPE_TOPIC)->where('goods_id', $tid);
    }

    public function scopePaid(Builder $query)
    {
        return $query->where('status', self::STATUS_PAY_SUCCESS)->whereNotNull('paid_at');
    }
}
